﻿using System;
using Autofac;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;

namespace Stock.Core.Common
{
    public class EFLogger:ILogger
    {
		private readonly string categoryName;
        private readonly ILoggerService _l;

        public EFLogger(string categoryName, ILoggerService l) 
        {
            this.categoryName = categoryName;
            _l = l; 
           
		}

		public bool IsEnabled(LogLevel logLevel)
		{
			return true;
		}

		public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
		{
            DbCommandLogData data = state as DbCommandLogData;
            _l.Log(new LogModel()
            {
                ExecuteStartTime = DateTime.Now,
                ExecutedTime = int.Parse(data.ElapsedMilliseconds.ToString()),
                Message = data.CommandText,
                ActionName = this.categoryName,
			}, "SQL");
		}

		public IDisposable BeginScope<TState>(TState state)
		{
			return null;
		}
    }

    public class NullLogger : ILogger
	{
		public bool IsEnabled(LogLevel logLevel)
		{
			return false;
		}

		public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
		{ }

		public IDisposable BeginScope<TState>(TState state)
		{
			return null;
		}
	}

	public class MyFilteredLoggerProvider : ILoggerProvider
	{
        private readonly IContainer _container;

        public MyFilteredLoggerProvider(IContainer container)
        {
            _container = container;
        }

		public ILogger CreateLogger(string categoryName)
		{
            // NOTE: 这里要注意,这是 EF Core 1.1的使用方式,如果你用的 EF Core 1.0, 就需把IRelationalCommandBuilderFactory替换成下面的类
            //       Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory

            if (categoryName == typeof(Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory).FullName
                || categoryName == typeof(IRelationalCommandBuilderFactory).FullName)
			{

				//ContainerBuilder builder = new ContainerBuilder();
				//var container = builder.Build();
				ILoggerService _l = _container.Resolve<ILoggerService>();
				return new EFLogger(categoryName, _l);
			}

			return new NullLogger();
		}
		public void Dispose()
		{ }
	}
}
